package com.my.security.controller;

import com.my.security.model.AuthenticationRequest;
import com.my.security.model.User;
import com.my.security.service.AuthenticationService;
import com.my.security.service.PermissionService;
import com.my.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author lbb
 * @fileName UserController
 * @description
 * @date 2020/5/12 0:34
 */
@Controller
public class UserController {
    @Autowired
    private AuthenticationService authenticationService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;

    @RequestMapping("/login")
    public String loginPage(){
        return "/login/login";
    }
    @RequestMapping("/logout")
    public String loginOut(HttpSession session){
        session.invalidate();
        return "/login/login";
    }

    @RequestMapping("/login2")
    public String login(AuthenticationRequest authenticationRequest, ModelMap modelMap, HttpSession httpSession){
        try{
            User user=authenticationService.authentication(authenticationRequest);
            httpSession.setAttribute(User.SECURITY_SESSION_USER_KEY,user);
            modelMap.put("nickName",user.getNickname());
            modelMap.put("roles",roleService.getUserRole(user.getUsername()));
            modelMap.put("userPermission",permissionService.getUserPermission(user.getUsername()));
            modelMap.put("permissions",permissionService.getList());
        }catch (RuntimeException e){
            modelMap.put("message",e.getMessage());
            return "login/login";
        }
        return "index";
    }

    @RequestMapping("/index")
    public String index( ModelMap modelMap){
        modelMap.put("nickName","游客");
        modelMap.put("permissions",permissionService.getList());
        return "index";
    }

    @RequestMapping("/resource/r1")
    public String test1(HttpSession httpSession,ModelMap modelMap){
        Object object=httpSession.getAttribute(User.SECURITY_SESSION_USER_KEY);
        if(object==null){
            modelMap.put("nickName","游客");
        }else {
            modelMap.put("nickName",((User)object).getNickname());
        }
        return "user/info";
    }

    @RequestMapping("/resource/r2")
    public String test2(HttpSession httpSession,ModelMap modelMap){
        Object object=httpSession.getAttribute(User.SECURITY_SESSION_USER_KEY);
        if(object==null){
            modelMap.put("nickName","游客");
        }else {
            modelMap.put("nickName",((User)object).getNickname());
        }
        return "user/list";
    }
}
